
# -*- coding: utf-8 -*-

import os
import time
import urllib2
import logging
from models.User import User
from models.Image import Image
from config import Config
from Webservices import getNameByUserIdFromWebService, loadUsersFromWebservice

def initializeModel():
	Image().delete()
	User().delete()
	loadUsersFromWebservice()
	loadImagesToDatabase("data/images")

def loadImagesToDatabase(path):
	for dirname, dirnames, filenames in os.walk(path):
		for subdirname in dirnames:
			subdirname = subdirname.decode("iso-8859-1")
			subject_path = os.path.join(dirname, unicode(subdirname))
			user = User.get_or_create(username=unicode(subdirname))
			if user:
				user.name = getNameByUserIdFromWebService(user.username)
				user.username = unicode(subdirname)
				user.save()
				for filename in os.listdir(subject_path):
					path = os.path.abspath(os.path.join(subject_path, filename))
					image = Image.get_or_create(path=path, user=user)
					image.save()

def getFilesCountByDirectoryPath(path):
	try:
		count = len([f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))])
	except:
		count = 0
	return count

def tryConnectToUsersServer():
	errors = 0
	connected = False

	while not connected:
		try:
			if errors > 20:
				exit()
			conn = urllib2.urlopen(urllib2.Request(Config.USERS_WEBSERVICE_URL))
			conn.close()
			connected = True
		except:
			errors += 1
			logging.error("Can't connect to Server: %s" % Config.USERS_WEBSERVICE_URL)
			logging.error("Retry in 5 seconds...")
			time.sleep(5)
